package org.light.pgsql.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Field;
import org.light.domain.Method;
import org.light.domain.Statement;
import org.light.exception.ValidateException;
import org.light.utils.DomainTokenUtil;
import org.light.utils.StringUtil;
import org.light.utils.TableStringUtil;
import org.light.utils.WriteableUtil;

public class SearchByFields extends org.light.verb.SearchByFields {
	public SearchByFields(Domain domain) throws ValidateException{
		super(domain);
	}
	
	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
			method.setNoContainer(true);
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(100L, 1, "<select id=\"" + method.getLowerFirstMethodName() + "\" resultMap=\""
					+ this.domain.getLowerFirstDomainName() + "\">"));
			list.add(new Statement(200L, 2, "select " + DomainTokenUtil.generateTableCommaFields(domain) + " from "
					+ domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain)));
			list.add(new Statement(300L, 2, "where 1=1 "));
			long serial = 400L;
			Set<Field> fields = this.domain.getSearchFields();
			for (Field f : fields) {
				if (f.getFieldType().equalsIgnoreCase("string")) {
					list.add(new Statement(serial, 2, "<if test=\"" + f.getLowerFirstFieldName() + "!=null and "
							+ f.getLowerFirstFieldName() + "!='' \">"));
					list.add(new Statement(serial + 100, 3,
							"and " + DomainTokenUtil.changeDomainFieldtoTableColum(f.getLowerFirstFieldName())
									+ " LIKE '%'|| #{" + f.getLowerFirstFieldName() + "}||'%'"));
				} else {
					list.add(new Statement(serial, 2, "<if test=\"" + f.getLowerFirstFieldName() + "!=null\">"));
					list.add(new Statement(serial + 100, 3,
							"and " + DomainTokenUtil.changeDomainFieldtoTableColum(f.getLowerFirstFieldName()) + " = #{"
									+ f.getLowerFirstFieldName() + "}"));
				}
				list.add(new Statement(serial + 200, 2, "</if>"));
				serial += 300L;
			}
	        if (this.domain.getDomainId()!=null) list.add(new Statement(serial + 50L, 2, " order by " + StringUtil.changeDomainFieldtoTableColum(domain.getDomainId().getFieldName()) + " asc "));
			list.add(new Statement(serial + 100L, 1, "</select>"));
			method.setMethodStatementList(WriteableUtil.merge(list));
			return method;
		}
	}

}
